const Koa = require('koa')
const WebSocket = require('ws');
const fs = require('fs');
const cors = require('koa2-cors')
// 引入路由
const router = require("koa-router")();
const path = require('path');


var data = fs.readFileSync(path.join(__dirname, './testData'), 'utf8');
var _data = data.split('$');
var ID = _data[0];

console.time()
var dataArray = _data.slice(2, _data.length - 1);
console.timeEnd();
console.log(dataArray.length);


var count = Math.ceil(dataArray.length / 5000)


const app = new Koa()
const ws = new WebSocket.Server({ port: 3001 });


ws.on('connection', ws => {
    console.log('server connection');
    // ws.on('message', msg => {});

    for (let i = 0; i < count; i++) {
        let str = dataArray.slice(i * 5000, (i + 1) * 5000);
        str.unshift('D');
        str.unshift(ID);
        setTimeout(() => {
            ws.send(str.join('$'));
        }, 200 * (i + 2))
    }

    ws.on('close', () => {
        console.log('server close');
    })
});


app.use(cors())
app.use(router.routes(), router.allowedMethods());
app.listen(3000)
